package com.ckerchina.admin.ckadmin.controller.console;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ckerchina.admin.ckadmin.controller.dto.MgrResponseData;
import com.ckerchina.admin.ckadmin.dao.AgentOrderDao;
import com.ckerchina.admin.ckadmin.domain.AgentOrder;
import com.ckerchina.admin.ckadmin.domain.mgr.MgrUser;
import com.ckerchina.admin.ckadmin.exception.ErrorCode;
import com.ckerchina.admin.ckadmin.exception.ZhuziException;
import com.ckerchina.admin.ckadmin.service.AgentOrderService;
import com.ckerchina.admin.ckadmin.service.UpdateService;
import com.ckerchina.admin.ckadmin.service.mgr.MgrUserDetail;
import com.ckerchina.admin.ckadmin.utils.Page;
import com.zhuzi.controller.dto.ResponseData;
import com.zhuzi.utils.JsonMapper;

@Controller
public class AgentOrderController extends AbstractConsoleController {

	@Autowired
	private AgentOrderDao agentOrderDao;
	@Autowired
	private AgentOrderService agentOrderService;

	@RequestMapping("agentorder/list")
	public @ResponseBody Page<AgentOrder> list(String teacher_id,String start_order_time,String end_order_time, String agentid, String customer_name, String state,int start,
			int limit) {
		
		logger.info(start_order_time);
		logger.info(end_order_time);
		String where = "";
		Map<String, Object> params = new HashMap<String, Object>();
		if (null != teacher_id && !"".equals(teacher_id)) {
			where += " and teacher_id = :teacher_id";
			params.put("teacher_id", teacher_id);
		}
		
		if (null != start_order_time && !"".equals(start_order_time)) {
			where += " and create_time >= :start_order_time";
			params.put("start_order_time", start_order_time);
		}
		
		if (null != end_order_time && !"".equals(end_order_time)) {
			where += " and create_time <= :end_order_time";
			params.put("end_order_time", end_order_time);
		}

		MgrUser user = getMgrUser();
		if (user.getActortype().equals("1"))// 代理商
		{
			where += " and agent_id = :agent_id";
			params.put("agent_id", user.getCompanyid());
		} else if (null != agentid && !"".equals(agentid)) {
			where += " and agent_id = :agentid";
			params.put("agentid", agentid);
		}

		if (null != customer_name && !"".equals(customer_name)) {
			where += " and customer_name LIKE :customer_name";
			params.put("customer_name", "%" + customer_name + "%");
		}
		
		if (null != state && !"".equals(state)) {
			where += " and state = :state";
			params.put("state", state);
		}

		logger.info("where: {}", where);
		logger.info("agent_id: {}",  user.getId().toString());

		return agentOrderDao.findPage(where, params, start, limit, " order by id desc");
	}

	/**
	 * 获取后台登录用户信息
	 */
	protected MgrUser getMgrUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			throw new ZhuziException(ErrorCode.MgrUser_Not_Exist);
		}
		MgrUserDetail userDetail = (MgrUserDetail) authentication.getPrincipal();
		logger.info("登录用户userName:{}", userDetail.getUsername());
		return userDetail.getUser();
	}

	@Autowired
	UpdateService updateService;

	@RequestMapping("agentorder/add")
	public @ResponseBody MgrResponseData add(AgentOrder finfo) {
		updateService.addAgentOrder(finfo);
		return new MgrResponseData("新增成功");
	}

	@RequestMapping("agentorder/update")
	public @ResponseBody MgrResponseData update(AgentOrder finfo) {
		logger.info("finfo {}",finfo);
		AgentOrder order = agentOrderDao.find(finfo.getId());
		
		logger.info("order {}",order);
		
		order.setRemark(finfo.getRemark());
		order.setCustomer_address(finfo.getCustomer_address());
		order.setCustomer_mobile(finfo.getCustomer_mobile());
		order.setCustomer_name(finfo.getCustomer_name());
		order.setCustomer_person(finfo.getCustomer_person());
		order.setState(finfo.getState());
		agentOrderService.merge(order);
		// updateService.updateAgentUser(finfo);
		return new MgrResponseData("修改成功");
	}

	@RequestMapping(value = "agentorder/uploadrequest")
	public @ResponseBody String upload(@RequestParam(value = "customer_request", required = false) MultipartFile file,
			@RequestParam(value = "id", required = false) String id) throws IOException {
		String fileName = saveFile(file);
		logger.info("fileName {}", fileName);
		logger.info("id: {}", id);
		AgentOrder order = agentOrderDao.find(Long.parseLong(id));
		logger.info("order:{}", order);
		order.setCustomer_request(fileName);
		// agentOrderService.mergeAgentOrder(order);
		agentOrderService.merge(order);
		ResponseData rd = new ResponseData();
		rd.setValue(ErrorCode.OK.memo);
		rd.setCode(ErrorCode.OK.value);
		logger.info(JsonMapper.toJson(rd));
		return JsonMapper.toJson(rd);
	}

	@RequestMapping(value = "agentorder/uploadcontract")
	public @ResponseBody String uploadcontract(
			@RequestParam(value = "customer_contract", required = false) MultipartFile file,
			@RequestParam(value = "id", required = false) String id) throws IOException {
		String fileName = saveFile(file);
		logger.info("fileName {}", fileName);
		logger.info("id: {}", id);
		AgentOrder order = agentOrderDao.find(Long.parseLong(id));
		logger.info("order:{}", order);
		// order.setCustomer_request(fileName);
		order.setCustomer_contract(fileName);
		// agentOrderService.mergeAgentOrder(order);
		agentOrderService.merge(order);
		ResponseData rd = new ResponseData();
		rd.setValue(ErrorCode.OK.memo);
		rd.setCode(ErrorCode.OK.value);
		logger.info(JsonMapper.toJson(rd));
		return JsonMapper.toJson(rd);
	}

	private String saveFile(MultipartFile file) throws IOException {
		String path = this.getClass().getResource("/../../").toString();
		path = path.replace("file:/", "");
		logger.info("path.indexOf(:)==0:" + String.valueOf(path.indexOf(":") == 0));
		if (path.indexOf(":") == -1) {
			path = "/" + path;
			logger.info("path2:" + path);
		}

		path = path + "attaches";

		String filename = file.getOriginalFilename();

		String format = filename.substring(filename.indexOf(".") + 1);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
		Random rd = new Random(10000);

		String name = sdf.format(new Date()) + "-" + rd.nextInt();
		String allPath = path + "/" + name + "." + format;
		logger.info("allpath {}", allPath);

		InputStream stream = file.getInputStream();
		FileOutputStream fs = new FileOutputStream(allPath);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();

		return name + "." + format;
	}
}
